package cn.com.anypay.manager.service.auth.strategy.impl;

import cn.com.anypay.manager.miaoma.sysuser.SysUserEntity;
import cn.com.anypay.manager.miaoma.sysuserauth.SysUserAuthEntity;
import cn.com.anypay.manager.service.auth.model.AuthRequest;
import cn.com.anypay.manager.service.auth.strategy.AbstractAuthStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 密码认证策略
 * 实现用户名密码认证逻辑
 */
@Slf4j
@Component
public class PasswordAuthStrategy extends AbstractAuthStrategy {

    @Override
    public String getAuthType() {
        return "password";
    }

    @Override
    protected boolean doAuthenticate(AuthRequest request, SysUserEntity user,
                                   HttpServletRequest servletRequest) {
        // 获取认证信息
        SysUserAuthEntity authEntity = sysUserAuthService.getByAuthTypeAndKey(
            getAuthType(), request.getIdentifier());

        if (authEntity == null) {
            log.warn("用户认证信息不存在: identifier={}", request.getIdentifier());
            return false;
        }

        // 检查认证状态
        if (!isAuthEntityValid(authEntity)) {
            log.warn("认证信息已禁用: identifier={}, status={}",
                request.getIdentifier(), authEntity.getStatus());
            return false;
        }

        // 检查是否被锁定
        if (isAccountLocked(authEntity)) {
            log.warn("账户被锁定: identifier={}, lockUntil={}",
                request.getIdentifier(), authEntity.getLockUntil());
            return false;
        }

        // 验证密码
        boolean passwordMatch = sysUserAuthService.verifyPassword(
            request.getCredential(), authEntity.getAuthCredentialValue());

        if (!passwordMatch) {
            log.warn("密码验证失败: identifier={}", request.getIdentifier());
            return false;
        }

        return true;
    }

    @Override
    protected SysUserEntity findOrCreateUser(AuthRequest request, HttpServletRequest servletRequest) {
        // 密码认证不创建新用户，只查找现有用户
        String identifier = request.getIdentifier();

        // 尝试通过用户名查找
        SysUserEntity user = sysUserService.getByUsername(identifier);
        if (user != null) {
            return user;
        }

        // 尝试通过邮箱查找
        user = sysUserService.getByEmail(identifier);
        if (user != null) {
            return user;
        }

        // 尝试通过手机号查找
        user = sysUserService.getByPhone(identifier);
        if (user != null) {
            return user;
        }

        log.warn("未找到用户: identifier={}", identifier);
        return null;
    }

    @Override
    protected void validateRequest(AuthRequest request) {
        super.validateRequest(request);

        // 密码认证的特殊验证
        if (request.getCredential().length() < 6) {
            throw new IllegalArgumentException("密码长度不能少于6位");
        }
    }
}